<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div >
        <el-form size="small" label-width="70px" :rules="rules" ref="form" :model="crud.order"
                 >
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编码">
                <el-input  v-model="crud.order.code" disabled placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select
                  v-model="crud.order.orderStatus"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="状态"
                  size="small"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <el-date-picker
                  :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                  v-model="crud.order.busDate"
                  type="date"
                  style="width: 100%;"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商" prop="customerId">
                <zSelect :value.sync="crud.order.customerId" :showName="crud.order.customerName" @getChange="getInfo" :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" url="api/dropDown/basCustomerList"  :params="{isContact:'1,2'}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="仓库" prop="warehouseId">
                <zSelect :value.sync="crud.order.warehouseId" :showName="crud.order.warehouseName"  :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" url="api/dropDown/basWarehouseList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="采购部门" prop="deptId" >
                <zSelect :value.sync="crud.order.deptId" :showName="crud.order.deptName"  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'" url="api/dropDown/childSysDeptList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="采购人员">
                <zSelect :value.sync="crud.order.userId" :showName="crud.order.userName" :label="crud.order.userName" :disabled="crud.order.deptId&&crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'" url="api/dropDown/sysUserList" :params="{deptId:crud.order.deptId}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--              <el-form-item label="到货日期" prop="acceptDate">-->
<!--                <el-date-picker-->
<!--                  v-model="crud.order.acceptDate"-->
<!--                  type="date"-->
<!--                  style="width: 100%;"-->
<!--                  :disabled="crud.order.orderStatus==='PASS'"-->
<!--                  default-value-->
<!--                  format="yyyy - MM - dd "-->
<!--                  value-format="yyyy-MM-dd"-->
<!--                  placeholder="选择日期">-->
<!--                </el-date-picker>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="是否追加" prop="isAppend">
                <el-select
                  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"
                  v-model="crud.order.isAppend"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in  dict.common_yes_or_no"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="验收状态">
                <el-select v-model="crud.order.isAccept" disabled class="edit-input" placeholder="请选择验收状态" style="width: 100%;">
                  <el-option
                    v-for="(item,index) in dict.common_yes_or_no"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="核销状态">
                <el-select v-model="crud.order.cancelStatus" class="edit-input" disabled placeholder="请选择核销状态" style="width: 100%;">
                  <el-option
                    v-for="(item,index) in dict.common_cancel_status"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源类型">
                <el-select
                  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"
                  v-model="crud.order.sourceType"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="系统自动生成"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in dict.t_buy_order_source_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value+''"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源编号">
                <el-input disabled  v-model="crud.order.sourceCode"  disabled  placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="采购渠道" prop="buyChannel">
                <el-select
                  v-model="crud.order.buyChannel"
                  class="filter-item"
                  clearable
                  placeholder="采购渠道"
                  size="small"
                  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in  dict.t_buy_order_buy_channel"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value + ''"
                  />
                </el-select>
              </el-form-item>

            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="采购单类型" prop="type">
                <el-select
                  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"
                  v-model="crud.order.type"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in dict.t_buy_order_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input  v-model="crud.order.remark"  placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据说明">
                <el-input  v-model="crud.order.orderRemark"  :disabled="crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"  placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--   操作栏   -->
      <div >
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          :disabled="crud.order.orderStatus==='PASS'"
          type="primary"
          @click="toAdd()"
          v-permission="permission.addDetail"
        >
          新增
        </el-button>
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="success"-->
        <!--          :disabled="crud.selections.length !== 1"-->
        <!--          @click="toDeatil(crud.selections)"-->
        <!--        >修改-->
        <!--        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          @click="submit()"
          v-permission="permission.add"
        >
          保存
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id=='null'"
          :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('PASS',id)"
          v-permission="permission.pass"
        >
          <!--        v-permission="permission.pass"-->
          审核
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.doDetailPassOrReject('REJECT',id)"
          v-permission="permission.reject"
        >
          <!--        v-permission="permission.reject"-->
          反审
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.order.orderStatus!=='SAVE'"
          :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('INVALID',id)"
          v-permission="permission.invalid"
        >
          <!--        v-permission="permission.pass"-->
          作废
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="crud.order.orderStatus!=='INVALID'"
          @click="crud.doDetailPassOrReject('RECOVER',id)"
          v-permission="permission.invalid"
        >
          <!--        v-permission="permission.reject"-->
          取消作废
        </el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          v-permission="permission.print"
        >打印</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          v-permission="permission.print"
        >打印预览</el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id=='null'"
          :loading="crud.passLoading"
          @click="crud.toAccept($route.params.id)"
          v-permission="permission.accept"
        >
          <!--        v-permission="permission.pass"-->
          验收
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.toUnAccept($route.params.id)"
          v-permission="permission.accept"
        >
          <!--        v-permission="permission.reject"-->
          反验收
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="crud.toCopy($route.params.id,'/buy/buyOrderDetail')"
          v-permission="permission.copy"
        >
          复制
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          @click="toAddList"
          v-permission="permission.batchAddDetail"
        >
          批量新增
        </el-button>
        <el-button
          slot="left"
          @click="showHistoryDialog = true"
          type="primary"
          size="mini"
          v-permission="permission.salesHistory"
        >
          采购记录
        </el-button>
        <el-button
          slot="left"
          @click="showPriceDialog = true"
          type="primary"
          size="mini"
          v-permission="permission.priceInfo"
        >
          价格信息
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.doDetailPassOrReject('REJECT',id)"

        >
          <!--        v-permission="permission.reject"-->
          查询采购数据分析
        </el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('up')"
        >上一页</el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('down')"
        >下一页</el-button>
      </div>
      <!--      :summary-method="crud.getSummaries"-->
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="buyOrder"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"
                        @removeStorage="removeStorage"
      >
      </vue-context-menu>
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header" @tabSave="tabSave" @pit="pit" />
      </el-dialog>
      <!--价格信息弹窗-->
      <j-dialog title=""
                style="width: 1000px"
                :visible.sync="showPriceDialog"
      >
        <price-detail
          orderType="BUY"
          :customerId="crud.order.customerId"
          :showAddBatchDialog.sync="showPriceDialog"
          @change="afterChangeGoods"></price-detail>
      </j-dialog>
      <el-table ref="table" row-class-name="crud.tableRowClassName"
                height="500px"
                :data="crud.data"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                size="small" style="width: 100%;"
                :show-summary="true"
                :summary-method="crud.sumRow"
                sortable="custom"
                border
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @sort-change="crud.sortChange"
                @selection-change="crud.selectionChangeHandler"
                @row-dblclick="switchRowIndex"
                highlight-current-row="highlight-current-row">

        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column :label="columnLabel(item)" v-if="item.visible" v-for="(item,index) in crud.header"   :prop="item.prop" :width="item.width">
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template>
              <span v-if="item.type == 1" :class="{red:crud.order.type === 2}">
                <span v-if="crud.order.type === 2" >
                  <span v-if="red.includes(item.prop)">
                  -{{scope.row[`${item.prop}`]}}
                  </span>
                  <span v-else>{{scope.row[`${item.prop}`]}}</span>
                </span>
                <span v-else>
                  {{scope.row[`${item.prop}`]}}
                </span>
            </span>
<!--              <span v-if="item.type == 1" :class="{red:crud.order.type === 2}" >-->
<!--                <span v-if="crud.order.type === 2" style="color: red">-->
<!--                  <span v-if="crud.order.type == 2 && isNegative.includes(item.prop)">-</span>-->
<!--                  {{scope.row[`${item.prop}`]}}-->
<!--                  <span v-if="red.includes(item.prop)">-->
<!--                  -{{scope.row[`${item.prop}`]}}-->
<!--                  </span>-->
<!--                  <span v-else>{{scope.row[`${item.prop}`]}}</span>-->
<!--                </span>-->
<!--                <span v-else>-->
<!--                  {{scope.row[`${item.prop}`]}}-->
<!--                </span>-->
<!--              </span>-->
              <span v-else-if="item.type == 2" :class="{red:crud.order.type === 2}" >{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-else-if="item.type == 3" :class="{red:crud.order.type === 2}" >{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
              <span v-else-if="item.type == 4" :class="{red:crud.order.type === 2}" >
                <span v-if="item.prop == 'goodsName'" >
                  <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.goodsName }}</span>
  <!--                  <jtg-select-plus v-else ref="productRef"-->
  <!--                                   v-model="scope.row.goodsId"-->
  <!--                                   :initValue="scope.row.goodsName"-->
  <!--                                   :customerId="crud.order.customerId"-->
  <!--                                   :type="crud.order.type"-->
  <!--                                   :buyChannel ="crud.order.buyChannel"-->
  <!--                                   @remoteMethod="getValue($event,scope.$index)"-->
  <!--                                   @input="getInput($event,scope.row.goodsName,scope.$index)"-->
  <!--                                   @change="crud.productChange($event,scope)"-->
  <!--                                   url="productList"/>-->
                  <el-input style="width: 450px" v-else placeholder="请输入商品" v-model="scope.row.goodsName" />
                </span>
                <span v-else-if="item.prop == 'goodsTagName'" >
                    <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.goodsTagName }}</span>
                    <zSelect v-else :value.sync="scope.row.goodsTagId" :showName="crud.order.goodsTagName"  :label="scope.row.goodsTagName"    @change="crud.setProduct($event,scope,'goodsTagName')" url="api/dropDown/basGoodsTagList"    style="width: 100%;"/>
                </span>
                <span v-else-if="item.prop == 'fuckNum'" >
                     <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'"><span v-if="crud.order.type == 2">-</span>{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
                      <el-input v-else
                                @input.native="crud.inuptCount(scope, 'boxNum')"
                                v-model="scope.row.boxNum"
                                style="width: 45%!important;">
                        <template slot="append" >{{scope.row.boxUnitName}}</template>
                      </el-input>
                      <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
                      <el-input v-else
                                @input.native="crud.inuptCount(scope, 'mainNum')"
                                v-model="scope.row.mainNum"
                                style="width: 45%!important;">
                              <template slot="append" >{{scope.row.mainUnitName}}</template>
                    </el-input>
                </span>
                <span v-else-if="item.prop == 'taxPrice'" >
                    <span v-if="scope.$index !== rowIndex || crud.order.isAccept === 1">{{ scope.row.taxPrice }}</span>
                    <el-input v-else
                              @input.native="crud.inuptCount(scope, 'taxPrice')"
                              oninput="value=value.replace(/[^\d^\.]/g,'')"
                              maxlength="12"
                              v-model.lazy="scope.row.taxPrice"
                              style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'taxBoxPrice'" >
                  <span v-if="scope.$index !== rowIndex  || crud.order.isAccept === 1">{{ scope.row.taxBoxPrice }}</span>
                          <el-input v-else
                                    @input.native="crud.inuptCount(scope, 'taxBoxPrice')"
                                    oninput="value=value.replace(/[^\d^\.]/g,'')"
                                    maxlength="12"
                                    v-model.lazy="scope.row.taxBoxPrice"
                                    style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'discountRate'" >
                  <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.discountRate }}%</span>
                  <el-input v-else
                            @input.native="crud.inuptCount(scope, 'discountRate')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.discountRate"
                            style="width: 100%">
                    <template slot="append">
                      %
                    </template>
                </el-input>
                </span>
                <span v-else-if="item.prop == 'warehouseName' " >
                    <span v-if="scope.$index !== rowIndex|| crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.warehouseName }}</span>
                <zSelect v-else v-model="scope.row.warehouseId" :showName="scope.row.warehouseName" class="edit-input"         @change="crud.setProduct($event,scope,'warehouseName')" :value.sync="scope.row.warehouseId" url="api/dropDown/basWarehouseList" />
              </span>
                <span v-else-if="item.prop == 'storehouseName' " >
                  <span v-if="scope.$index !== rowIndex || crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'">{{ scope.row.storehouseName }}</span>
                  <zSelect v-else :value.sync="scope.row.storehouseId" :showName="scope.row.storehouseName" @change="crud.setProduct($event,scope,'storehouseName')" :params="{warehouseId:scope.row.warehouseId}"  url="api/dropDown/basStorehouseList"    style="width: 100%;"/>
                </span>
                <span v-else-if="item.prop == 'acceptBoxNum'" >
                    <span >{{ scope.row.acceptBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>
                    <span >{{ scope.row.acceptMainNum || 0 }}{{ scope.row.mainUnitName }}</span>
                </span>
                <span v-else-if="item.prop == 'tax'" >
                    <span>{{ scope.row.taxRate }}%</span>
                  </span>
                <span v-else-if="item.prop == 'remark'" >
                   <span v-if="scope.$index !== rowIndex">{{ scope.row.remark }}</span>
                    <el-input v-else
                              type="textarea"
                              :rows="2"
                              v-model.lazy="scope.row.remark"
                              style="width: 100%"/>
                </span>
                <span v-else-if="item.prop == 'taxAmount'"  class="flex a-item j-content">
                    <span v-if="scope.$index !== rowIndex || crud.order.isAccept === 1"><span v-if="crud.order.type == 2">-</span>{{ scope.row.taxAmount }}</span>
                      <el-input v-else         oninput="value=value.replace(/[^\d^\.]/g,'')"
                                maxlength="12"  @input.native="crud.inuptCount(scope, 'taxAmount')" v-model="scope.row.taxAmount"
                                placeholder="请输入内容">
                      </el-input>
                </span>
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader"  label="操作" fixed="right" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus==='PASS'"
              style="border: none;width: auto;height: auto"
              @click="delAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
<!--        -->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.goodsName }}</span>-->
<!--            <jtg-select-plus v-else ref="productRef"-->
<!--                             v-model="scope.row.goodsId"-->
<!--                             :initValue="scope.row.goodsName"-->
<!--                             :customerId="crud.order.customerId"-->
<!--                             :type="crud.order.type"-->
<!--                             :buyChannel ="crud.order.buyChannel"-->
<!--                             @remoteMethod="getValue($event,scope.$index)"-->
<!--                             @input="getInput($event,scope.row.goodsName,scope.$index)"-->
<!--                             @change="crud.productChange($event,scope)"-->
<!--                             url="productList"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="helpSign" label="助记符" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('model')" prop="model" label="规格型号" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('barcode')" prop="barcode" label="条形码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTypeName')" prop="goodsTypeName" label="分类" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="商品品牌" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="goodsTagName" label="商品类型" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.goodsTagName }}</span>-->
<!--            <zSelect v-else :value.sync="scope.row.goodsTagId" :label="scope.row.goodsTagName"    @change="crud.setProduct($event,scope,'goodsTagName')" url="api/dropDown/basGoodsTagList"    style="width: 100%;"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxUnitCount')" prop="boxUnitCount" label="箱装量" />  ;-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('firstUnitName')" prop="firstUnitName" label="单位" width="100">  ;-->
<!--&lt;!&ndash;          <template slot-scope="scope">  ;-->
<!--&lt;!&ndash;            <span v-if="!scope.row.isSelected">{{ scope.row.firstUnitName }}{{ scope.row.firstUnitName }}</span>  ;-->
<!--&lt;!&ndash;           <zSelect v-if="scope.row.isSelected" :value.sync="scope.row.firstUnitId" :label="scope.row.firstUnitName" url="api/dropDown/basUnitList">  ;-->
<!--&lt;!&ndash;            </zSelect>  ;-->
<!--&lt;!&ndash;          </template>  ;-->
<!--&lt;!&ndash;        </el-table-column>  ;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="箱数" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="零数" >  ;-->
<!--&lt;!&ndash;        </el-table-column>  ;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxUnitId')" prop="boxUnitId" label="辅数量" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>-->
<!--            <el-input v-if="scope.row.isSelected"-->
<!--                      @input.native="crud.inuptCount(scope, 'boxNum')"-->
<!--                      v-model="scope.row.boxNum"-->
<!--                      style="width: 45%!important;">-->
<!--              <template slot="append" >{{scope.row.boxUnitName}}</template>-->
<!--            </el-input>-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>-->
<!--            <el-input v-if="scope.row.isSelected"-->
<!--                      @input.native="crud.inuptCount(scope, 'mainNum')"-->
<!--                      v-model="scope.row.mainNum"-->
<!--                      style="width: 45%!important;">-->
<!--              <template slot="append" >{{scope.row.mainUnitName}}</template>-->
<!--            </el-input>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" >-->
<!--          <template slot-scope="scope">-->
<!--            <span >{{ scope.row.goodsCount }}</span>-->
<!--&lt;!&ndash;            <el-input v-if="scope.row.isSelected"  ;-->
<!--&lt;!&ndash;                      @input.native="crud.inuptCount(scope, 'goodsCount')"  ;-->
<!--&lt;!&ndash;                      oninput="value=value.replace(/[^\d^\.]/g,'')"  ;-->
<!--&lt;!&ndash;                      maxlength="12"  ;-->
<!--&lt;!&ndash;                      v-model.lazy="scope.row.goodsCount"  ;-->
<!--&lt;!&ndash;                      style="width: 100%"/>  ;-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('oldTaxPrice')" prop="oldTaxPrice" label="原单价" />-->

<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="采购价" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.taxPrice }}</span>-->
<!--            <el-input v-if="scope.row.isSelected"-->
<!--                      @input.native="crud.inuptCount(scope, 'taxPrice')"-->
<!--                      oninput="value=value.replace(/[^\d^\.]/g,'')"-->
<!--                      maxlength="12"-->
<!--                      v-model.lazy="scope.row.taxPrice"-->
<!--                      style="width: 100%"/>-->
<!--          </template>-->
<!--        </el-table-column>-->

<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('oldTaxBoxPrice')" prop="oldTaxBoxPrice" label="原箱价" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxBoxPrice')" prop="taxBoxPrice" label="采购箱价" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.taxBoxPrice }}</span>-->
<!--                        <el-input v-if="scope.row.isSelected"-->
<!--                                  @input.native="crud.inuptCount(scope, 'taxBoxPrice')"-->
<!--                                  oninput="value=value.replace(/[^\d^\.]/g,'')"-->
<!--                                  maxlength="12"-->
<!--                                  v-model.lazy="scope.row.taxBoxPrice"-->
<!--                                  style="width: 100%"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('discountRate')" prop="discountRate" label="折扣率" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.discountRate }}%</span>-->
<!--                        <el-input v-if="scope.row.isSelected"-->
<!--                                  @input.native="crud.inuptCount(scope, 'discountRate')"-->
<!--                                  oninput="value=value.replace(/[^\d^\.]/g,'')"-->
<!--                                  maxlength="12"-->
<!--                                  v-model.lazy="scope.row.discountRate"-->
<!--                                  style="width: 100%">-->
<!--                          <template slot="append">-->
<!--                            %-->
<!--                          </template>-->
<!--                        </el-input>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader"  v-if="columns.visible('warehouseName')" prop="warehouseName" label="仓库" width="200">-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.warehouseName }}</span>-->
<!--            <zSelect v-else v-model="scope.row.warehouseId" class="edit-input"         @change="crud.setProduct($event,scope,'warehouseName')" :value.sync="scope.row.warehouseId" url="api/dropDown/basWarehouseList" />-->
<!--          </template>-->
<!--        </el-table-column>-->

<!--        <el-table-column :render-header="crud.renderHeader"  v-if="columns.visible('storehouseName')" prop="storehouseName" label="库位" width="200">-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.storehouseName }}</span>-->
<!--            <zSelect v-else :value.sync="scope.row.storehouseId" @change="crud.setProduct($event,scope,'storehouseName')" :params="{warehouseId:scope.row.warehouseId}"  url="api/dropDown/basStorehouseList"    style="width: 100%;"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount" label="含税金额" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxAmount')" prop="noTaxAmount" label="未税金额" />-->
<!--          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('tax')" prop="tax" label="税额" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('discountAmount')" prop="discountAmount" label="折扣金额" />-->
<!--        &lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="acceptBoxNum" label="验收箱数" />  ;-->
<!--        &lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="acceptMainNum" label="验收零数" />  ;-->
<!--        &lt;!&ndash;          <template slot-scope="scope">  ;-->
<!--        &lt;!&ndash;            <span v-if="!scope.row.isSelected">{{ scope.row.taxAmount }}</span>  ;-->
<!--        &lt;!&ndash;            <el-input v-if="scope.row.isSelected"  ;-->
<!--        &lt;!&ndash;                      oninput="value=value.replace(/[^\d^\.]/g,'')"  ;-->
<!--        &lt;!&ndash;                      maxlength="12"  ;-->
<!--        &lt;!&ndash;                      v-model.lazy="scope.row.taxAmount"  ;-->
<!--        &lt;!&ndash;                      style="width: 100%"/>  ;-->
<!--        &lt;!&ndash;          </template>  ;-->
<!--          &lt;!&ndash;          <template slot-scope="scope">  ;-->
<!--          &lt;!&ndash;            <span v-if="!scope.row.isSelected">{{ scope.row.noTaxAmount }}</span>  ;-->
<!--          &lt;!&ndash;            <el-input v-if="scope.row.isSelected"  ;-->
<!--          &lt;!&ndash;                      oninput="value=value.replace(/[^\d^\.]/g,'')"  ;-->
<!--          &lt;!&ndash;                      maxlength="12"  ;-->
<!--          &lt;!&ndash;                      v-model.lazy="scope.row.noTaxAmount"  ;-->
<!--          &lt;!&ndash;                      style="width: 100%"/>  ;-->
<!--          &lt;!&ndash;          </template>  ;-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" />  ;-->

<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('acceptBoxNum')" prop="acceptBoxNum" label="验收辅数量" >-->
<!--          <template slot-scope="scope">-->
<!--            <span >{{ scope.row.acceptBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>-->
<!--            <span >{{ scope.row.acceptMainNum || 0 }}{{ scope.row.mainUnitName }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('acceptGoodsCount')" prop="acceptGoodsCount" label="验收数量" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('acceptTaxAmount')" prop="acceptTaxAmount" label="验收金额" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('volume')" prop="volume" label="总体积" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('weight')" prop="weight" label="总重量" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxRate ')" prop="tax" label="税率" >-->
<!--          <template slot-scope="scope">-->
<!--                <span>{{ scope.row.taxRate }}%</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxName')" prop="taxName" label="税额" />  ;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"  >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="!scope.row.isSelected">{{ scope.row.remark }}</span>-->
<!--            <el-input v-if="scope.row.isSelected"-->
<!--                      type="textarea"-->
<!--                      :rows="2"-->
<!--                      v-model.lazy="scope.row.remark"-->
<!--                      style="width: 100%"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        &lt;!&ndash;        v-permission="['admin','buyProtocolDetail:edit','buyProtocolDetail:del']"  ;-->
<!--        <el-table-column :render-header="crud.renderHeader"  label="操作" fixed="right" width="150px" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            &lt;!&ndash;              <el-button  ;-->
<!--            &lt;!&ndash;                type="primary"  ;-->
<!--            &lt;!&ndash;                icon="el-icon-plus"  ;-->
<!--            &lt;!&ndash;                circle  ;-->
<!--            &lt;!&ndash;                v-if="(crud.data.length-1)==scope.$index"  ;-->
<!--            &lt;!&ndash;                :disabled="crud.order.orderStatus==='PASS'"  ;-->
<!--            &lt;!&ndash;                @click="crud.addRow(scope.$index)"></el-button>  ;-->
<!--            &lt;!&ndash;              v-if="crud.data.length!==1"  ;-->
<!--            <el-button-->
<!--              slot="reference" class="el-icon-delete opration_icon_btn"-->
<!--              :disabled="crud.order.orderStatus==='PASS'"-->
<!--              style="border: none;width: auto;height: auto"-->
<!--              @click="delAddRow(scope.$index)"></el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
<!--      <pagination />-->
      <!--批量新增弹窗-->
      <el-dialog :close-on-click-modal="false" title="商品新增"
                 :visible.sync="showAddBatchDialog" append-to-body width="100vw">
        <add-batch v-if="showAddBatchDialog" :showAddBatchDialog.sync="showAddBatchDialog" :list="detailList"
                   :params="{customerId:crud.order.customerId,type:crud.order.type==1?'BUY':'BUY_RETURN',buyChannel:1}"
                   @change="afterChangeGoods"></add-batch>
      </el-dialog>
      <el-dialog  title="打印预览"
                  destroy-on-close
                  v-dialogDrag
                  close-on-press-escape
                  :visible.sync="showPdf" append-to-body width="50vw">
        <j-pdf :src="pdfSrc" ></j-pdf>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="选择商品"
                 destroy-on-close
                 v-dialogDrag
                 close-on-press-escape
                 :modal="false"
                 :visible.sync="showQueryGoods" append-to-body width="50vw">
        <j-goods-select :customerId="crud.order.customerId" :buyChannel="crud.order.buyChannel"  @closeDialog="closeDialog" :type="crud.order.type==1?'BUY':'BUY_RETURN'" @diaLogGoodsChange="changeGoods" v-if="showQueryGoods"  :queryGoods="queryGoods" :noReturnBox="false"></j-goods-select>
      </el-dialog>
      <j-dialog title="采购记录"
                v-dialogDrag
                v-show="showHistoryDialog"
                :visible.sync="showHistoryDialog"
                style="width: 80%"
      >

        <history  historyType="BUY" :historyDialog="showHistoryDialog" :customerId="crud.order.customerId"
                 :showAddBatchDialog.sync="showHistoryDialog" @change="afterChangeGoods"></history>
      </j-dialog>
    </div>
  </div>
</template>

<script>
import crudBuyOrder from '@/api/erp/buyOrder'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import { getCompany } from '@/api/system/company'
import {Notification} from "element-ui";
import addBatch from '@/components/addBatch/addBatch'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import {salesDetailKey} from "@/utils/key";
import {tablemixins} from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import jGoodsSelect from "@/components/jGoodsSelect/jGoodsSelect";
import history from '../salesOrder/history'
import jDialog from '../../../components/jDialog/jDialog'
import priceDetail from '../salesOrder/priceDetail.vue'
// crud交由presenter持有
const defaultCrud = CRUD({ title: '采购单明细',
  params() {
    const href = location.href.split('/')
    if(href[5].includes('copyId')){
      return {
        id: 0,
      }
    }else{
      return {
        id: href[href.length - 1].split('?')[0] == 'add' ? 0 : href[href.length - 1].split('?')[0],  page: 0, size: 999,
        // id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1].split('?')[0],  page: 0, size: 999,
      }
    }
  },
  url: 'api/buyOrder/detail',name:'buyOrderDetail', sort: 't.seq,asc', crudMethod: { ...crudBuyOrder }})
const defaultForm = { id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null , idList: [],}
export default {
  name: 'buyOrderDetail',
  components: { pagination, crudOperation, rrOperation, udOperation,jtgSelectPlus,addBatch,jPrintConfig, jTableColumnConfig, jGoodsSelect, history, jDialog, priceDetail},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),salesDetailKey,salesDetailKey,tablemixins],
  dicts: ['t_buy_order_source_type','common_yes_or_no','t_buy_order_type','common_order_status','t_buy_order_buy_channel','t_bas_unit_type','common_cancel_status'],

  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  data() {
    return {
      id: null,
      showPriceDialog:false,
      permission: {
        add: ['admin', 'buyOrder:add'],
        edit: ['admin', 'buyOrder:edit'],
        del: ['admin', 'buyOrder:del'],
        import: ['admin', 'buyOrder:import'],
        export: ['admin', 'buyOrder:export'],
        copy: ['admin', 'buyOrder:copy'],
        upload: ['admin', 'buyOrder:upload'],
        download: ['admin', 'buyOrder:download'],
        pass: ['admin', 'buyOrder:pass'],
        reject: ['admin', 'buyOrder:reject'],
        closed: ['admin', 'buyOrder:closed'],
        invalid: ['admin', 'buyOrder:invalid'],
        stop: ['admin', 'buyOrder:stop'],
        recover: ['admin', 'buyOrder:recover'],
        print: ['admin', 'buyOrder:print'],
        addDetail: ['admin', 'buyOrder:addDetail'],
        batchAddDetail: ['admin', 'buyOrder:batchAddDetail'],
        accept: ['admin', 'buyOrder:accept'],
      },
      isNegative:['cancelAmount','unCancelAmount','taxAmount','noTaxAmount','tax','discountAmount',
        'oldTaxAmount','oldNoTaxAmount','oldTax','acceptTaxAmount','acceptNoTaxAmount','acceptTax','boxNum','mainNum','acceptBoxNum','acceptMainNum',
        'acceptBoxCount','goodsCount','boxCount'],
      red:['goodsCount','boxCount','taxAmount','noTaxAmount','tax','discountAmount','acceptGoodsCount','acceptBoxCount','oldTaxAmount','oldNoTaxAmount','oldTax','acceptTaxAmount','acceptNoTaxAmount','acceptTax','boxNum','mainNum','acceptBoxNum','acceptMainNum','cancelAmount','unCancelAmount'],
      // red: ['cancelAmount','unCancelAmount','taxAmount','noTaxAmount','tax','discountAmount',
      //   'oldTaxAmount','oldNoTaxAmount','oldTax','acceptTaxAmount','acceptNoTaxAmount','acceptTax','boxNum','mainNum','acceptBoxNum','acceptMainNum',
      //     'acceptBoxCount','goodsCount','boxCount'],
      // red:['acceptBoxCount','goodsCount','boxCount','boxCount','taxAmount','noTaxAmount','discountAmount','acceptTaxAmount','acceptNoTaxAmount',],
      rules: {
        deptId: [
          { required: true, message: '采购部门不能为空', trigger: 'blur' }
        ],
        acceptDate: [
          { required: true, message: '到货日期不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '采购单类型不能为空', trigger: 'blur' }
        ],
        buyChannel: [
          { required: true, message: '渠道类型不能为空', trigger: 'blur' }
        ],
        // sourceType: [
        //   { required: true, message: '来源类型不能为空', trigger: 'blur' }
        // ],
        customerId: [
          { required: true, message: '供应商不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '业务员不能为空', trigger: 'blur' }
        ],
        isAppend: [
          { required: true, message: '是否追加不能为空', trigger: 'blur' }
        ],
        isContact: [
          { required: true, message: '是否第三方采购不能为空', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '仓库不能为空', trigger: 'blur' },
          {
            validator(r, v, cb) {
              if (v < 1) {
                return cb('仓库不能为空');
              }
              cb()
            }
            , message: '仓库不能为空', trigger: 'blur'
          }
        ],
      },
      showHistoryDialog:false,
      addRowData:{
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      },
      showAddBatchDialog: false,
      productList:[],
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [{
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        },
          {
            fnHandler: 'removeStorage', // 绑定事件
            icoName: 'el-icon-delete', // icon图标
            btnName: '清除缓存' // 菜单名称
          },
        ]
      },
      queryGoods:{
        index:null,
        keyword: '',
      },
      showQueryGoods: false,
      idDate: null
    }
  },
  // watch: {
  //   'crud.data':{
  //     handler(n,o){
  //       console.log(11)
  //       if (!this.crud.data[0].isUpdate){
  //         this.crud.data[0].isUpdate=true
  //         for (let i in this.crud.data) {
  //           for (let key in this.crud.data[i]) {
  //             if (this.red.includes(key) && this.crud.data[i].type === 2) {
  //               this.crud.data[i][key] = Number(this.crud.data[i][key]) * -1
  //               console.log(this.crud.data[i][key])
  //             }
  //           }
  //         }
  //       }
  //     },
  //     deep:true
  //   }
  // },
  destroyed() {
    this.crud.setItemInfo("buyOrderDetail_add")
  },
  created(){
    let id = this.$route.query.id
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      console.log('route.query', this.$route.params)
      let  strs = this.$route.params.id.split("=");
      this.crud.toGetCopyInfo(strs[1])
    }
    const data ={
      modelName:'buyOrderDetail',
      url: "api/buyOrder/detail",
      userId:this.$store.state.user.user.userId,
    }
    this.crud.headerInfo = {
      code:'buyOrderDetail',
      userId:this.$store.state.user.user.userId,
      path: "api/buyOrder/detail",
    }
    if(/add$/.test(window.location.href)){
      getHeaderProperties(data).then(res=>{
        this.crud.header = JSON.parse(res.data.header.content)
        console.log(this.crud.header)
        this.$forceUpdate()
      }).catch(err=>{console.log(err)})
    }
    if (this.$route.params.id == 'add') {
      console.log('cleanItemInfo')
      if( this.crud.getItemInfo("buyOrderDetail_add")){
        return false
      }
        this.crud.order = {
          id: null,
          code: '',
          busDate:  this.getTime(),
          // createTime: this.getTime(),
          name: '',
          userId: '',
          deptId: null,
          type: 1,
          buyChannel: '1',
          acceptDate: null,
          isContact: null,
          isAppend: 0,
          orderStatus: 'SAVE',
          index: '0',
          customerId:'',
          contactName:'',
          contactPhone:'',
          startDate: null,
          endDate: null,
          remark: '',
        }
    }
  },
  mounted() {
    if(/add$/.test(window.location.href)){
      // this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
    }else {
      this.idDate = this.$route.query.idDate
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
    }

    // this.$refs.table = this.$refs.table.$children[0]
  },
  beforeUpdate() {
    if (this.$route.params.id != 'add') {
      this.id = this.$route.params.id
      this.query.id = this.id
      this.crud.order.id = this.id
    }
  },
  methods: {
    init(){
      this.crud.order = {
        id: null,
        code: '',
        busDate:  this.getTime(),
        // createTime: this.getTime(),
        name: '',
        userId: '',
        deptId: null,
        type: 1,
        buyChannel: '1',
        acceptDate: null,
        isContact: null,
        isAppend: 0,
        orderStatus: 'SAVE',
        index: '0',
        customerId:'',
        contactName:'',
        contactPhone:'',
        startDate: null,
        endDate: null,
        remark: '',
      }
      this.crud.data = []
    },
    switchRowIndex(row) {
        if (row.index === this.rowIndex) {
          this.rowIndex = -1
          return
        }
        this.rowIndex = row.index
      },
    closeDialog(val){
      this.showQueryGoods = false
    },

    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.crud.data.map(detail=>detail.goodsId)
      let _goods = []
      let result = []
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true
        this.crud.data.push(good)
        // }
      })
      // this.calcuForm()
    },
    toAddList() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //校验通过
          this.showAddBatchDialog = true
        } else {
          if (!this.crud.order.customerId) {
            this.$message.error("请先选择客户")
          }
          if (!this.crud.order.type) {
            this.$message.error("请先选择销售单类型")
          }
          if (!this.crud.order.buyChannel) {
            this.$message.error("请先选择采购渠道")
          }
        }
      })
    },
    changeGoods(val){
      this.showQueryGoods = false
      this.crud.diaLogGoodsChange(val)
      this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
    },
    getInfo(e){
      this.$set(this.crud.order,'warehouseId',e.warehouseId)
      this.crud.order.warehouseName = e.warehouseName
      this.crud.order.deptName = e.deptName
      this.crud.order.deptId = e.deptId
      this.crud.order.userId = e.userId
      this.crud.order.userName = e.userName
      if (this.crud.data.length === 0){
      this.crud.data.push({
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      })}
    },
    delAddRow(i){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delRow(i)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else{
        this.crud.delRow(i)
      }
    },
    removeStorage(){
      localStorage.removeItem('buyOrderDetail_add')
      this.$message({
        type: 'success',
        message: '清除成功!'
      })
    },
    getValue(e,i){
      console.log('this.crud.data',this.crud.data )
      this.crud.data[i].productName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if(item.existBox === null){
          item.existBox = 0
        }
        if(item.occupyBox === null){
          item.occupyBox = 0
        }
      })
    },
    getInput(e,name,i){
      if(this.crud.data){
        if(e){
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= e
        }else{
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= null
        }
      }
    },
    // 保存
    submit(){
      var oDate1 = new Date(this.crud.order.startDate);
      var oDate2 = new Date(this.crud.order.endDate);
      if(oDate1.getTime() > oDate2.getTime()){
        this.$message({
          message: '开始日期不能大于结束日期',
          type: 'warning'
        })
        this.crud.order.startDate = null
        this.crud.order.endDate = null
        return false
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const table_rules = [
          {name: '数量', value: 'goodsCount'},
          // {name: '采购价', value: 'taxPrice'},
          // {name: '未税单价', value: 'noTaxPrice'},
          // {name: '含税金额', value: 'taxAmount'},
          // {name: '未税金额', value: 'noTaxAmount'}
        ]
        const result = table_rules.some(({name, value}) => {
          const rules = this.$refs.table.data.some((item, index) => {
            if (!this.tableRules((index + 1), name, item[value])) return true
          })
          if (rules) return true
        })
        if (!result) this.save()
      })
    },
    tableRules(index, name, value) {
      if (!value) {
        Notification.error({title: '序号【' + index + '】' + name + '不能为空'})
        return false
      } else return true
    },
    getTime(date = new Date()){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.order.detailList  = this.crud.data
      let params = this.crud.order
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = null
      }
      if (this.crud.order.orderStatus === 'PASS' || this.crud.order.orderStatus==='CLOSE'){
        params.isEditWithoutReject = 1
      }
      crudBuyOrder.add(params).then(res => {
        if(res.success){
          this.crud.order  = res.data
          // this.crud.data = res.data.detailList
          let id=res.data.id
          if(this.$route.params.id == 'add' || href[5].includes('copyId')){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo('buyOrderDetail_add')
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.refresh()
          that.crud.loadingClose()
        }else{
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res)=>{
        that.crud.loadingClose()
      })
    },
    // 新增
    toAdd(){

      if(!this.crud.order.customerId){
        this.$message({
          message: '请先选择供应商',
          type: 'error'
        })
        return false
      }
      if(!this.crud.order.type){
        this.$message({
          message: '请先选择采购单类型',
          type: 'error'
        })
        return false
      }
      if(!this.crud.order.buyChannel){
        this.$message({
          message: '请先选择采购渠道',
          type: 'error'
        })
        return false
      }
      this.crud.data.push({
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      })
    },
    //修改
    toDetail(){
    },
    detailJump(type){
      console.log(this.idList)
      if (this.idList.length){
        if (type ==='up'){
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== 0){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/buy/buyOrderDetail/${this.idList[index-1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
        console.log(this.$route.params.id)
        }else {
          const index = this.idList.findIndex(item=>item == this.crud.order.id)
          if (index !== this.idList.length-1){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path:`/buy/buyOrderDetail/${this.idList[index+1]}?idDate=${this.idDate}`})
          }else {
            this.$message.error('没有更多数据了')
          }
          console.log()
        }
      }
    },
    toEdit(row) {
      let id = 0
      if (row) {
        id = row.id
      }
      this.$router.push({
        path: 'buyOrderDetail/' + id,
        query: {id: id},
      })
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },

  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.red{
  color: red;
}
</style>

